<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseAdminController;
use App\Lib\Enum\ValRule;
use App\Lib\Logger;
use App\Lib\Validates;
use App\Models\TagGroup;
use App\Rules\CheckRule;
use App\Service\TagService;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class TagController extends BaseAdminController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //标签列表
        $data = (new TagService())->getTagList2([]);
        return view("admin.tag.index",["tags"=>$data]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if ($this->request->isMethod("get")) {
            return view("admin.tag.create_tag");
        } else {
            $params = $this->request->all();
            $params['site_id'] = getCurrentSiteId();
            //参数验证
            $params = (new CheckRule($params, ValRule::TAG, ValRule::TAG_MSG))->check();
            if ($params["error"] > 0) {
                return $this->error($params['error'], $params['msg']);
            }
            return $this->store($params["data"]);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store($params)
    {
        //插入
        $result = (new TagService())->add($params);
        if (!empty($result)) {
            return $this->success($result, "添加成功");
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::TAG, 'store', '添加失败', $params);
        return $this->error(70000, "添加失败");
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.tags.index", "标签不存在", "error");
        }

        if ($this->request->isMethod("get")) {
            $data = (new TagService())->getTagById($id);
            return view("admin.tag.edit",["tag"=>$data]);
        } else {
            $params = $this->request->all();
            return $this->update($id,$params);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update($id,$params)
    {
        //参数验证
        $params = (new CheckRule($params, ValRule::TAG, ValRule::TAG_MSG))->check();
        if ($params["error"] > 0) {
            return $this->error($params['error'], $params['msg']);
        }
        //更新
        $result = (new TagService())->update($id,$params["data"]);
        if(!$result){
            $this->log(Logger::LOG_LEVEL_ERROR,Logger::TAG,'update',"修改标签[ID:{$id}],失败",$params);
            return $this->error( 80000, "更新失败");
        }
        return $this->success("","更新成功");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //验证
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.tags.index", "id必须是正整数", "error");
        }
        // todo 删除前需验证
        //删除
        $result = (new TagService())->destroy($id);
        if (!$result) {
            $this->log(Logger::LOG_LEVEL_ERROR, Logger::TAG, 'destroy', "标签{$id}删除失败", ['del_id' => $id]);
            return $this->error(80001, "删除失败");
        }
        return $this->layuiDataSuccess("", 0, "删除成功");
    }

    /**分组*/
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function tagGroup()
    {
        //获取数据
        $tagService = new TagService();
        $data = $tagService->getTagGroupList(0);
        $data = $tagService->getArrToStr($data,"tags","name","tags");
        //获取应用范围
        foreach($data as $k=>$d){
            $scope = $tagService->getScope($d["scope"]);
            $data[$k]["scope"] = $tagService->getArrToStr($scope,"","name","scope")["scope"];
        }
        return view("admin.tag_group.index",["group"=>$data]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function groupCreate()
    {
        if ($this->request->isMethod("get")) {
            $scope=(new TagService())->getScope();
            $tags=(new TagService())->getTagList([]);
            return view('admin.tag_group.create',["scope"=>$scope,"tags"=>$tags]);
        } else {
            $params = $this->request->all();
            //参数验证
            $params = (new CheckRule($params["data"], ValRule::TAG_GROUP, ValRule::TAG_GROUP_MSG))->check();
            if ($params["error"] > 0) {
                return $this->tempLaravelError("admin.tags.create.attach", $params['msg']);
            }
            return $this->groupStore($params["data"]);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function groupStore($params)
    {
        $tagService = new TagService();
        //添加
        $tagGroup = $tagService->addGroup($tagService->getGroupData($params));
        //返回信息
        if (!empty($tagGroup)) {
            //添加
            $tagAndGroup = $tagService->addTagGroupTag($tagGroup["id"],$params);
            if (!empty($tagAndGroup)) {
                return $this->tempNotice("admin.tags.index.attach", "添加成功");
            }
            $this->log(Logger::LOG_LEVEL_ERROR, Logger::TAG, 'groupStore', "标签组[ID:{$tagGroup["id"]}]分配标签失败", $params);
            return $this->tempLaravelError("admin.tags.create.attach", "分配标签失败");
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::TAG, 'groupStore', '添加失败', $params);
        return $this->tempLaravelError("admin.tags.create.attach", "添加失败");
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function groupShow($id)
    {

    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function groupEdit($id)
    {
        //验证
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.tags.index.attach", "标签不存在", "error");
        }
        if ($this->request->isMethod("get")) {
            $info = (new TagService())->info($id);
            return view('admin.tag_group.edit',["tags"=>$info['tagsSelect'],"info"=>$info]);
        } else {
            $params = $this->request->all();
            //参数验证
            $params = (new CheckRule($params["data"], ValRule::TAG_GROUP, ValRule::TAG_GROUP_MSG))->check();
            if ($params["error"] > 0) {
                return $this->tempLaravelError("admin.tags.update.attach", $params["msg"],["id"=>$id]);
            }
            return $this->groupUpdate($id,$params["data"]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function groupUpdate($id,$params)
    {
        //获取数据
        $data = (new TagService())->getGroupData($params);
        //更新标签组
        $updateGroup = (new TagService())->updateGroup($id,$data);
        if($updateGroup){
            //更新标签组中的标签
            $tagAndGroup=(new TagService())->updateTagInGroup($id,$params);
            if (!empty($tagAndGroup)) {
                return $this->tempNotice("admin.tags.index.attach", "更新成功");
            }
            $this->log(Logger::LOG_LEVEL_ERROR, Logger::TAG, 'groupUpdate', "标签组[ID:{$id}]更新标签失败", $params);
            return $this->tempLaravelError("admin.tags.update.attach", "更新标签失败",["id"=>$id]);
        }
        $this->log(Logger::LOG_LEVEL_ERROR, Logger::TAG, 'groupUpdate', "更新标签组[ID:{$id}]失败", $params);
        return $this->tempLaravelError("admin.tags.update.attach", "更新失败",["id"=>$id]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function groupDestroy($id)
    {
        //验证
        $check = Validates::isPositiveInteger($id);
        if (!$check) {
            return $this->tempNotice("admin.tags.index.attach", "id必须是正整数", "error");
        }
        // todo 删除前需验证
        //删除
        $result = (new TagService())->destroyGroup($id);
        if (!$result) {
            $this->log(Logger::LOG_LEVEL_ERROR, Logger::TAG, 'groupDestroy', "标签组{$id}删除失败", ['del_id' => $id]);
            return $this->error(80001, "删除失败");
        }
        return $this->layuiDataSuccess("", 0, "删除成功");
    }
}
